/**   
 * @Title: LotteryInfoListAct.java 
 * @Package com.esun.rabbit2.viewer.mainact.lotteryinfoact 
 * @Description: (开奖信息列表Activity) 
 * @Author Billy qigs@500wan.com   
 * @Date 2011-6-20 上午10:34:08  
 * Copyright (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.rabbit2.viewer.mainact.lotteryinfoact;

import java.util.ArrayList;
import java.util.Hashtable;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.Toast;

import android.widget.TextView;

import com.esun.config.Config;
import com.esun.config.Key;
import com.esun.config.Language;
import com.esun.model.LotteryInfo;
import com.esun.network.ConnectionChangeReceiver;
import com.esun.network.communicater.LotteryInfoCommunicater;
import com.esun.rabbit2.viewer.mainact.lotteryhallact.DaletouAgp;
import com.esun.rabbit2.viewer.mainact.lotteryhallact.ShuangseqiuAgp;
import com.esun.rabbit2.viewer.mainact.lotteryinfoact.PullToRefreshListView.OnRefreshListener;
import com.esun.ui.R;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;

/**
 * @ClassName: LotteryInfoListAct
 * @Description: (开奖信息列表Activity)
 * @author Billy qigs@500wan.com
 * @date 2011-6-10 上午10:28:09
 * 
 */
public class LotteryInfoListAct extends Activity implements OnScrollListener {
	private PullToRefreshListView listViewLotteryInfo; // 自定义listview
	private ItemAdapter itemAdapter;
	private ArrayList<Hashtable<String, String>> alItem; // 列表数据存储
	private boolean isRunning, isFooterExist;
	private boolean isFirstLoad = true; // 是否是第一次加载
	private boolean isNoMoreRecord = true; // 是否还有记录
	private boolean isShow = false;// 是否显示没有更多记录提示
	private boolean isBottomChanged = true;
	private LinearLayout linearFooter; // listview底部footer布局
	private LinearLayout linearNoMore;
	private Handler handlerGetHistoryLotteryInfo;
	private LotteryInfoCommunicater historyLotteryInfoCommunicater; // 开奖记录接口
	private final int Get_LotteryInfo_SUCCEED = 1001; // 与服务器通信成功、失败
	private final int Get_LotteryInfo_FAIL = 1002;
	private final int FOOTER_VIEW_TAG = 10000;
	private final int FOOTER_VIEW_TAG2 = 20000;
	private final String Get_refresh_LotteryInfo = "0"; // 获取当前最新数据标示
	private final String Get_LotteryInfo_Num = "15"; // 每次通信获得数据条数
	private String lotid; // 通信所需参数彩种
	private String type;
	private String expect; // 通信所需参数期号（0为当前最新开奖信息）
	private String recordsinpage; // 通信所需参数每次取得记录条数
	private String serverMessage; // 服务器返回信息
	private String strBottomExpect; // 已经取得的最后一条记录的期号
	private int refreshORBottom = 2; // state=1刷新 state=2到底部
	// private static int LIST_SHOW_NUM = 30;
	private int itemLayoutResourse;

	private ProgressDialog progressDialog;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.lotteryinfolist_act);

		initUI();// 初始化
		initHandler();

	}

	// 初始化
	public void initUI() {
		// 取得传入彩种
		Bundle bundle = this.getIntent().getExtras();
		lotid = bundle.getString(Key.KEY_LOTID);
		EDebug.o(bundle.getString(Key.KEY_LOTID));
		type = bundle.getString(Key.KEY_TYPE);

		// // 判断彩种
		if (lotid.equals(Config.RENXUANJIU) || lotid.equals(Config.SHENGFUCAI)) {
			itemLayoutResourse = R.layout.lotteryinfo_list_table_sfcrxj;
		} else {
			itemLayoutResourse = R.layout.lotteryinfo_list_table;
		}

		if (lotid.equals(Config.RENXUANJIU)) {
			lotid = Config.SHENGFUCAI;
		}

		progressDialog = ViewerUtil.showProgressDialog(LotteryInfoListAct.this, getResources().getString(R.string.loading_text));
		progressDialog.show();

		recordsinpage = Get_LotteryInfo_Num;
		isRunning = false;
		isFooterExist = true;
		strBottomExpect = Get_refresh_LotteryInfo;
		expect = Get_refresh_LotteryInfo;

		listViewLotteryInfo = (PullToRefreshListView) findViewById(R.id.lotteryinfolistact_listview_lotteryInfoList);
		linearFooter = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.lotteryinfoact_linear_footer, null);
		linearNoMore = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.lotteryrecordlist_act_linear_nomore, null);
		linearFooter.setTag(FOOTER_VIEW_TAG);
		linearNoMore.setTag(FOOTER_VIEW_TAG2);

		alItem = new ArrayList<Hashtable<String, String>>();

		itemAdapter = new ItemAdapter(this, alItem, itemLayoutResourse);
		listViewLotteryInfo.addFooterView(linearFooter);// 增加底部状态条
		listViewLotteryInfo.setAdapter(itemAdapter);
		listViewLotteryInfo.removeFooterView(linearFooter);

		// item点击响应事件
		listViewLotteryInfo.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				if (arg2 <= alItem.size()) {
					if (!lotid.equals(Config.SHIYIXUANWU)) {
						if (lotid.equals(Config.RENXUANJIU) || lotid.equals(Config.SHENGFUCAI)) {
							Intent intent = new Intent();
							intent.setClass(LotteryInfoListAct.this, LotteryInfoDetailAct.class);
							Bundle bundle = new Bundle();
							bundle.putString(Key.KEY_LOTID, lotid);
							bundle.putString(Key.KEY_EXPECT, alItem.get(arg2 - 1).get("lotteryIssue").toString());
							intent.putExtras(bundle);
							startActivity(intent);
						}else {
							Bundle bundleJump = new Bundle();
							bundleJump.putString(Key.KEY_LOTID, lotid);
							bundleJump.putString(Key.KEY_EXPECT, alItem.get(arg2 - 1).get("lotteryIssue").toString());
							bundleJump.putString(Key.KEY_TYPE, type);
							bundleJump.putString(Key.KEY_LOTTERYNUMRED, alItem.get(arg2 - 1).get(Key.KEY_LOTTERYNUMRED).toString());
							bundleJump.putString(Key.KEY_LOTTERYNUMBLUE, alItem.get(arg2 - 1).get(Key.KEY_LOTTERYNUMBLUE).toString());
							String opentime = (alItem.get(arg2 - 1).get(Key.KEY_OPENTIME).toString().split(Config.ONESPACE))[0].toString();
							bundleJump.putString(Key.KEY_OPENTIME, opentime);
							jumpToLatestdetail(bundleJump);
						}
						
					}
				}
			}
		});
		// 刷新事件
		listViewLotteryInfo.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				if (!isRunning) {
					isRunning = true;
					isNoMoreRecord = true;
					refreshORBottom = 1;
					expect = Get_refresh_LotteryInfo;
					listViewLotteryInfo.removeFooterView(linearNoMore);
					getHistoryLotteryInfoThread();

				}
			}
		});

		listViewLotteryInfo.setOnScrollListener(this);

	}

	// 与服务器通信线程
	public void getHistoryLotteryInfoThread() {
		new Thread() {
			@Override
			public void run() {
				historyLotteryInfoCommunicater = new LotteryInfoCommunicater();
				Message msg = new Message();
				try {
					boolean isSucceed = historyLotteryInfoCommunicater.isGetHistoryLotInfo(lotid, expect, recordsinpage);
					serverMessage = historyLotteryInfoCommunicater.getMsgServer();
					if (isSucceed) {
						msg.what = Get_LotteryInfo_SUCCEED;
					} else {
						msg.what = Get_LotteryInfo_FAIL;
					}
					handlerGetHistoryLotteryInfo.sendMessage(msg);
				} catch (Exception e) {
					msg.what = Config.CONNECTION_FAIL;
					handlerGetHistoryLotteryInfo.sendMessage(msg);
				}
			}
		}.start();
	}

	// 消息处理
	public void initHandler() {
		handlerGetHistoryLotteryInfo = new Handler() {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case Get_LotteryInfo_SUCCEED:
					communicateSucceed(historyLotteryInfoCommunicater.getLotteryInfoList());
					if (historyLotteryInfoCommunicater.getLotteryInfoList().size() < Integer.valueOf(Get_LotteryInfo_Num)) {
						listViewLotteryInfo.addFooterView(linearNoMore);
						isNoMoreRecord = false;
					}
					if (refreshORBottom == 1) {
						listViewLotteryInfo.onRefreshComplete();
					}
					break;

				case Get_LotteryInfo_FAIL:
					isBottomChanged = false;
					listViewLotteryInfo.removeFooterView(linearFooter);
					if (refreshORBottom == 1) {
						listViewLotteryInfo.onRefreshComplete();
					}
					if (historyLotteryInfoCommunicater.getState() == 202) {
						isNoMoreRecord = false;
						listViewLotteryInfo.addFooterView(linearNoMore);
					} else {
						if (isShow) {
							// ViewerUtil.showTipDialog(LotteryInfoListAct.this, serverMessage, false);
							Toast.makeText(LotteryInfoListAct.this, serverMessage, Toast.LENGTH_SHORT).show();
						}
					}
					break;

				case Config.CONNECTION_FAIL:
					isBottomChanged = false;
					if (refreshORBottom == 1) {
						listViewLotteryInfo.onRefreshComplete();
					}
					listViewLotteryInfo.removeFooterView(linearFooter);
					if (isShow) {
						// ViewerUtil.showTipDialog(LotteryInfoListAct.this, Language.STR_CONNECTIONFAIL, false);
						Toast.makeText(LotteryInfoListAct.this, Language.STR_CONNECTIONFAIL, Toast.LENGTH_SHORT).show();
					}
					break;

				default:
					break;
				}
				progressDialog.cancel();
				isRunning = false;
			}
		};
	}

	// 处理取得的开奖信息
	public ArrayList<Hashtable<String, String>> getHistoryLotteryInfo(ArrayList<LotteryInfo> list) {
		ArrayList<Hashtable<String, String>> listTemp = new ArrayList<Hashtable<String, String>>();
		strBottomExpect = list.get(list.size() - 1).getExpect();
		char douhao = ',';
		char space = ' ';
		String line = "\\|";

		if (lotid.equals(Config.SHUANGSEQIU) || lotid.equals(Config.DALETOU)) {
			for (int i = 0; i < list.size(); i++) {
				String[] strTmp = list.get(i).getLotteryNum().split(line);

				Hashtable<String, String> map = new Hashtable<String, String>();
				map.put(Key.KEY_LOTTERYISSUE, list.get(i).getExpect());
				map.put(Key.KEY_OPENTIME, list.get(i).getOpentime());
				map.put(Key.KEY_LOTTERYNUMRED, strTmp[0].replace(douhao, space));
				map.put(Key.KEY_LOTTERYNUMBLUE, strTmp[1].replace(douhao, space));
				listTemp.add(map);
			}
		} else if (lotid.equals(Config.FUCAI3D)) {
			for (int i = 0; i < list.size(); i++) {
				Hashtable<String, String> map = new Hashtable<String, String>();
				map.put(Key.KEY_LOTTERYISSUE, list.get(i).getExpect());
				map.put(Key.KEY_OPENTIME, list.get(i).getOpentime());
				map.put(Key.KEY_LOTTERYNUMRED, list.get(i).getLotteryNum().replace(douhao, space));
				map.put(Key.KEY_LOTTERYNUMBLUE, "");
				listTemp.add(map);
			}
		} else {
			for (int i = 0; i < list.size(); i++) {
				Hashtable<String, String> map = new Hashtable<String, String>();
				map.put(Key.KEY_LOTTERYISSUE, list.get(i).getExpect());
				map.put(Key.KEY_OPENTIME, list.get(i).getOpentime());
				map.put(Key.KEY_LOTTERYNUMRED, list.get(i).getLotteryNum().replace(douhao, space));
				map.put(Key.KEY_LOTTERYNUMBLUE, "");
				listTemp.add(map);
			}
		}
		return listTemp;
	}

	// 通讯成功处理
	public void communicateSucceed(ArrayList<LotteryInfo> list) {
		ArrayList<Hashtable<String, String>> listMapTemp = new ArrayList<Hashtable<String, String>>();
		listMapTemp = getHistoryLotteryInfo(list);
		// 刷新或到底分别处理
		if (refreshORBottom == 1) {
			alItem.clear();
			for (int i = 0; i < listMapTemp.size(); i++) {
				alItem.add(alItem.size(), listMapTemp.get(i));
			}
			// listViewLotteryInfo.onRefreshComplete();
		} else if (refreshORBottom == 2) {
			for (int i = 0; i < listMapTemp.size(); i++) {
				alItem.add(alItem.size(), listMapTemp.get(i));
			}
			listViewLotteryInfo.removeFooterView(linearFooter);
			isFooterExist = false;
		}
		itemAdapter.notifyDataSetChanged();
	}

	// 到底事件
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0) {
			if (isNoMoreRecord) {
				if (isFirstLoad) {
					listViewLotteryInfo.removeFooterView(linearFooter);
					isFooterExist = false;
					listViewLotteryInfo.prepareForRefresh();
					listViewLotteryInfo.onRefresh();
					isFirstLoad = false;
				} else {
					if (!isRunning && alItem.size() != 0 && isBottomChanged) {
						EDebug.o(this, "到底刷新" + "=====" + alItem.size());
						isRunning = true;
						if (isFooterExist == false) {
							listViewLotteryInfo.addFooterView(linearFooter);
						}
						refreshORBottom = 2;
						expect = strBottomExpect;
						getHistoryLotteryInfoThread();
						itemAdapter.notifyDataSetChanged();
					}
				}
			}
		} else {
			isBottomChanged = true;
		}

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	protected void onPause() {
		super.onPause();
		isShow = false;
		this.unregisterReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver());
	}

	@Override
	protected void onResume() {
		super.onResume();
		isShow = true;
		this.registerReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver(), ConnectionChangeReceiver.getIntentFilter());
	}

	// 将menu键点击事件返回给父activity处理
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU || keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
			Activity parent = getParent();
			if (parent != null) {
				parent.onKeyDown(keyCode, event);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onTrackballEvent(MotionEvent event) {
		Activity parent = getParent();
		if (parent != null) {
			parent.onTrackballEvent(event);
			return true;
		}
		return false;
	}

	class ItemAdapter extends BaseAdapter {
		private LayoutInflater listInflater;
		private ArrayList<Hashtable<String, String>> listTemp;
		private int layid;

		public ItemAdapter(Context context, ArrayList<Hashtable<String, String>> listTemp, int layid) {
			this.listInflater = LayoutInflater.from(context);
			this.listTemp = listTemp;
			this.layid = layid;
		}

		@Override
		public int getCount() {

			return listTemp.size();
		}

		@Override
		public Object getItem(int position) {

			return listTemp.get(position);
		}

		@Override
		public long getItemId(int position) {

			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			EDebug.o("getView被调用~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			if (convertView == null) {
				convertView = listInflater.inflate(layid, null);
			}
			String RedNum = listTemp.get(position).get(Key.KEY_LOTTERYNUMRED);
			String BlueNum = listTemp.get(position).get(Key.KEY_LOTTERYNUMBLUE);
			EDebug.o("RedNum--------------" + RedNum);
			EDebug.o("BlueNum-------------" + BlueNum);
			TextView tvExpect = (TextView) convertView.findViewById(R.id.lotteryinfo_listtable_tv_issue);
			if (!(lotid.equals(Config.SHENGFUCAI) || lotid.equals(Config.RENXUANJIU))) {
				TextView tvDate = (TextView) convertView.findViewById(R.id.lotteryinfo_listtable_tv_date_time);
				String time = listTemp.get(position).get(Key.KEY_OPENTIME);
				tvDate.setText(time);
				LinearLayout llNum = (LinearLayout) convertView.findViewById(R.id.lotteryinfo_listtable_ll_lotterynum);
				String[] redNum = RedNum.split(Config.ONESPACE);
				llNum.removeAllViews();
				// MarginLayoutParams params = new MarginLayoutParams(50, 50);

				for (int i = 0; i < redNum.length; i++) {
					if (redNum[i] != null && !redNum[i].equals(Config.NULLMARK)) {
						LinearLayout llRedNum = new LinearLayout(LotteryInfoListAct.this);
						if (i != 0) {
							llRedNum.setPadding(10, 0, 0, 0);
							if (i == redNum.length - 1) {
								llRedNum.setPadding(10, 0, 10, 0);
							}
						}

						TextView tvRedNum = new TextView(LotteryInfoListAct.this);
						tvRedNum.setText(redNum[i].toString());
						tvRedNum.setTextColor(getResources().getColor(R.color.white));
						tvRedNum.setBackgroundResource(R.drawable.img_ball_red_36x39);
						tvRedNum.setGravity(Gravity.CENTER);
						tvRedNum.setTextSize(15);
						llRedNum.addView(tvRedNum);

						// tvRedNum.setLayoutParams(params);
						llNum.addView(llRedNum);
					}
				}
				if (BlueNum != null && !BlueNum.equals(Config.NULLMARK)) {
					String[] blueNum = BlueNum.split(Config.ONESPACE);
					for (int i = 0; i < blueNum.length; i++) {
						if (blueNum[i] != null && !blueNum[i].equals(Config.NULLMARK)) {
							LinearLayout llBlueNum = new LinearLayout(LotteryInfoListAct.this);
							llBlueNum.setPadding(10, 0, 0, 0);
							TextView tvBlueNum = new TextView(LotteryInfoListAct.this);
							tvBlueNum.setText(blueNum[i]);
							tvBlueNum.setTextSize(15);
							tvBlueNum.setTextColor(getResources().getColor(R.color.white));
							tvBlueNum.setBackgroundResource(R.drawable.img_ball_blue_36x39);
							tvBlueNum.setGravity(Gravity.CENTER);
							// tvBlueNum.setLayoutParams(params);
							llBlueNum.addView(tvBlueNum);
							llNum.addView(llBlueNum);
						}
					}
				}
			} else {
				TextView tv_RedNum = (TextView) convertView.findViewById(R.id.lotteryinfo_listtable_tv_numRed);
				TextView tv_BlueNum = (TextView) convertView.findViewById(R.id.lotteryinfo_listtable_tv_numBlue);
				tv_RedNum.setText(RedNum);
				tv_BlueNum.setText(BlueNum);
			}

			String expect = listTemp.get(position).get(Key.KEY_LOTTERYISSUE);
			tvExpect.setText(expect);

			return convertView;
		}

	}

	private void jumpToLatestdetail(Bundle bundle) {

		Activity parent = (Activity) LotteryInfoListAct.this.getParent();
		String name = parent.getClass().getName();
		Message msg = new Message();
		msg.what = LatestdetailsAct.JUMPTOLATESTDETAIL;
		msg.setData(bundle);
		if (name.equals(LotteryInfoListAgp.class.getName())) {

			((LotteryInfoListAgp) parent).jumpToCurrentInfo(msg);

		} else if (name.equals(ShuangseqiuAgp.class.getName())) {

			((ShuangseqiuAgp) parent).jumpToCurrentInfo(msg);
		} else if (name.equals(DaletouAgp.class.getName())) {

			((DaletouAgp) parent).jumpToCurrentInfo(msg);
		} else {
			EDebug.o(LotteryInfoListAct.this,"没有匹配项");
		}
	}

}
